import {sendLoginRequest, storeUserInfo} from "@/utils/userUtils";

const user = {
	state: {
		uid: '',
		username: '',
		password: '',
		isPhoto: null,
		isConfigue: null,
		roleId: '',
		phone: '',
		email: '',
		loginStatus: false
	},
	mutations: {
		SET_UID: (state, uid) => {
			state.uid = uid
		},
		SET_USERNAME: (state, username) => {
			state.username = username
		},
		SET_PASSWORD: (state, password) => {
			state.password = password
		},
		SET_ISPHOTO: (state, isPhoto) => {
			state.isPhoto = isPhoto
		},
		SET_ISCONFIGUE: (state, isConfigue) => {
			state.isConfigue = isConfigue
		},
		SET_ROLEID: (state, roleId) => {
			state.roleId = roleId
		},
		SET_PHONE: (state, phone) => {
			state.phone = phone
		},
		SET_EMAIL: (state, email) => {
			state.email = email
		},
		SET_LOGIINSTATUS: (state, loginStatus) => {
			state.loginStatus = loginStatus
		}
	},
	actions: {
		setUid (context, data) {
			context.commit('SET_UID', data)
		},
		setUsername (context, data) {
			context.commit('SET_USERNAME', data)
		},
		setRoleId (context, data) {
			context.commit('SET_ROLEID', data)
		},
		setIsphoto (context, data) {
			context.commit('SET_ISPHOTO', data)
		},
		setIsconfigue (context, data) {
			context.commit('SET_ISCONFIGUE', data)
		},
		setPassword (context, data) {
			context.commit('SET_PASSWORD', data)
		},
		setPhone (context, data) {
			context.commit('SET_PHONE', data)
		},
		setEmail (context, data) {
			context.commit('SET_EMAIL', data)
		},
		setLoginStatus (context, data) {
			context.commit('SET_LOGIINSTATUS', data)
		},

		Login ({commit}, option) {
			return new Promise((resolve, reject) => {
				let uid = ''
				let username = ''
				let roleId = ''
				let isPhoto = null
				let isConfigue = null
				sendLoginRequest(option).then((response) => {
					let data = response
					// console.log(data)
					if (data.code == '200') {
						uid = data.uid
						username = data.username
						roleId = data.role_id
						isPhoto = data.is_photo
						isConfigue = data.is_configue

						commit('SET_UID',uid)
						commit('SET_USERNAME',username)
						commit('SET_ROLEID',roleId)
						commit('SET_ISPHOTO',isPhoto)
						commit('SET_ISCONFIGUE',isConfigue)
						commit('SET_LOGIINSTATUS',true)

						let authReq = {
							username: option.username,
							password: option.password,
							uid: uid,
							roleId: roleId,
							isPhoto: isPhoto,
							isConfigue: isConfigue
						}
						storeUserInfo(authReq)
						resolve(data)
						// console.log(data)
					}
					else {
						resolve(data)
						// console.log(data)
					}
				}).catch((error) => {
					reject(error)
					// console.log(error)
				})
			})
		}
	}
}

export default user
